package cn.appsys.controller.backend;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.service.AppCategoryService;
import cn.appsys.service.AppInfoService;
import cn.appsys.service.AppVersionService;
import cn.appsys.service.DataDictionaryService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;

@Controller
@RequestMapping(value = "/manager/backend/app")
public class AppController {
	private Logger logger = Logger.getLogger(AppController.class);

	@Resource
	private AppInfoService appInfoService;
	@Resource
	private AppVersionService appVersionService;
	@Resource
	private DataDictionaryService dataDictionaryService;
	@Resource
	private AppCategoryService appCategoryService;

	@RequestMapping(value = "/list")
	public String list(@RequestParam(value = "querySoftwareName", required = false) String softwareName,
			@RequestParam(value = "queryStatus", required = false) String statusName,
			@RequestParam(value = "queryFlatformId", required = false) String flatformName,
			@RequestParam(value = "queryCategoryLevel1", required = false) String categoryLevel1Name,
			@RequestParam(value = "queryCategoryLevel2", required = false) String categoryLevel2Name,
			@RequestParam(value = "queryCategoryLevel3", required = false) String categoryLevel3Name,
			HttpServletRequest request, @RequestParam(value = "pageIndex", required = false) String pageIndex) {
		// 查询基础信息表
		List<AppInfo> appInfoList = new ArrayList<AppInfo>();
		// 设置页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		int currentPageNo = 1;
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "redirect:/error";
			}
		} else {
			currentPageNo = 0;
		}
		// 总数量（表）
		int totalCount = appInfoService.devUserCount(flatformName, categoryLevel1Name, categoryLevel2Name,
				categoryLevel3Name, statusName, softwareName);
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);

		int totalPageCount = pages.getTotalPageCount();

		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		int currentPageNos = (currentPageNo - 1) * pageSize;
		// 查询App状态
		List<DataDictionary> statusList = new ArrayList<DataDictionary>();
		statusList = dataDictionaryService.appStatusList();

		// 查询所属平台
		List<DataDictionary> flatFormList = new ArrayList<DataDictionary>();
		flatFormList = dataDictionaryService.flatformList();

		// 查询一级标签
		List<AppCategory> categoryLevel1List = new ArrayList<AppCategory>();
		categoryLevel1List = appCategoryService.categoryLevel(null);

		//二级分类列表和三级分类列表---回显
		if(categoryLevel2Name != null && !categoryLevel2Name.equals("")){
			List<AppCategory> categoryLevel2List = appCategoryService.categoryLevel(Integer.parseInt(categoryLevel1Name));
			request.setAttribute("categoryLevel2List", categoryLevel2List);
		}
		if(categoryLevel3Name != null && !categoryLevel3Name.equals("")){
			List<AppCategory> categoryLevel3List = appCategoryService.categoryLevel(Integer.parseInt(categoryLevel2Name));
			request.setAttribute("categoryLevel3List", categoryLevel3List);
		}
		
		// 查询App基础信息
		appInfoList = appInfoService.list(flatformName, categoryLevel1Name, categoryLevel2Name, categoryLevel3Name,
				statusName, softwareName, currentPageNos, pageSize);
		request.setAttribute("categoryLevel1List", categoryLevel1List);
		request.setAttribute("statusList", statusList);
		request.setAttribute("flatFormList", flatFormList);
		request.setAttribute("appInfoList", appInfoList);
		request.setAttribute("pages", pages);
		request.setAttribute("queryStatus", statusName);
		request.setAttribute("queryFlatformId", flatformName);
		request.setAttribute("queryCategoryLevel1", categoryLevel1Name);
		request.setAttribute("queryCategoryLevel2", categoryLevel2Name);
		request.setAttribute("queryCategoryLevel3", categoryLevel3Name);

		return "backend/applist";
	}

	/**
	 * 跳转到APP信息审核页面
	 * 
	 * @param appId
	 * @param versionId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.GET)
	public String check(@RequestParam(value = "aid", required = false) String appId,
			@RequestParam(value = "vid", required = false) String versionId, Model model) {
		AppInfo appInfo = null;
		AppVersion appVersion = null;
		try {
			appInfo = appInfoService.getAppInfo(Integer.parseInt(appId));
			appVersion = appVersionService.findIdvVersion(Integer.parseInt(versionId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute(appVersion);
		model.addAttribute(appInfo);
		return "backend/appcheck";
	}

	@RequestMapping(value = "/checksave", method = RequestMethod.POST)
	public String checkSave(AppInfo appInfo) {
		logger.debug("appInfo =========== > " + appInfo.getStatus());
		try {
			if (appInfoService.updateSatus(appInfo.getStatus(), appInfo.getId())) {
				return "redirect:/manager/backend/app/list";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "backend/appcheck";
	}

	/**
	 * 查询分级
	 * 
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/categorylevellist.json", produces = "application/json; charset=utf-8")
	@ResponseBody
	public Object level(@RequestParam(value = "pid", required = true) Integer parentId) throws Exception {
		Map<String, Object> map = null;
		List<Object> list = new ArrayList<Object>();
		List<AppCategory> appCateList = appCategoryService.categoryLevel(parentId);
		for (AppCategory appCategory : appCateList) {
			map = new HashMap<String, Object>();
			map.put("id", appCategory.getId());
			map.put("categoryName", appCategory.getCategoryName());
			list.add(map);
		}
		return JSONArray.toJSONString(list);
	}

}
